﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace CommonManagement
{
    /// <summary>
    /// 天气应用服务类
    /// </summary>
    public class WeatherAppService : ApplicationService, IWeatherAppService
    {
        private readonly static DateTime today = new DateTime(2022, 4, 21);
        private readonly IRepository<Weather, int> _forecastRepository;

        public WeatherAppService(
            IRepository<Weather, int> forecastRepository)
        {
            _forecastRepository = forecastRepository;
        }

        // 当天天气
        public async Task<ResultResponse<WeatherDto>> TodayAsync()
        {
            var todayEntity = await _forecastRepository
                .Include(m => m.TempInfo)
                .Include(m => m.Wind)
                .Include(m => m.ComfortLevel)
                .Include(m => m.AirQuantity)
                .SingleOrDefaultAsync(m => m.Date == today);
            var dtoToday = ObjectMapper.Map<Weather, WeatherDto>(todayEntity);
            return ResultResponse<WeatherDto>.Successful(dtoToday);
        }

        // 预报天气
        public async Task<ResultResponse<ForecastDto>> ForecastAsync()
        {
            var todayEntity = await _forecastRepository
                .Include(m => m.TempInfo)
                .Include(m => m.Wind)
                .Include(m => m.ComfortLevel)
                .Include(m => m.AirQuantity)
                .Include(m => m.Divisions)
                .SingleOrDefaultAsync(m => m.Date == today);
            var dtoToday = ObjectMapper.Map<Weather, TodayDto>(todayEntity);
            var start = today.AddDays(-1);
            var end = today.AddDays(6);
            var forecastList = await _forecastRepository
                .Where(m => m.Date >= start && m.Date <= end)
                .OrderBy(m => m.Date)
                .ToListAsync();
            var dtosList = ObjectMapper.Map<List<Weather>, List<WeatherDto>>(forecastList);
            var dto = new ForecastDto()
            {
                Today = dtoToday,
                WeatherList = dtosList
            };
            return ResultResponse<ForecastDto>.Successful(dto);
        }
    }
}